package com.myhome.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myhome.config.constant.R;
import com.myhome.domain.RolePrivilegesParam;
import com.myhome.domain.SysPrivilege;
import com.myhome.service.SysPrivilegeService;
import com.myhome.service.SysRolePrivilegeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;


/**
 * @author 乔轶欣
 */
@RestController
@Api(tags = "权限操作")
@RequestMapping("/privileges")
public class SysPrivilegeController {
    @Autowired
    SysPrivilegeService sysPrivilegeService;
    @Autowired
    SysRolePrivilegeService sysRolePrivilegeService;

    @GetMapping
    @ApiOperation("查询所有权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "页面显示数目")
    })
    @PreAuthorize("hasAuthority('sys_privilege_query')")
    public R<Page<SysPrivilege>> getAllPrivileges(@ApiIgnore Page<SysPrivilege> page) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysPrivilege> pageResult = sysPrivilegeService.page(page);
        return R.ok(pageResult);
    }

    @PostMapping
    @ApiOperation("新增权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysPrivilege", value = "权限数据")
    })
    @PreAuthorize("hasAuthority('sys_privilege_create')")
    public R insertPrivilege(@RequestBody @Validated SysPrivilege sysPrivilege) {
        boolean isSave = sysPrivilegeService.save(sysPrivilege);
        if (isSave) {
            return R.ok("新增成功");
        }
        return R.fail("新增失败");
    }

    @PatchMapping
    @ApiOperation("修改权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysPrivilege", value = "将要修改时数据")
    })
    @PreAuthorize("hasAuthority('sys_privilege_update')")
    public R updatePrivilege(@RequestBody @Validated SysPrivilege sysPrivilege) {
        boolean isUpdate = sysPrivilegeService.updateById(sysPrivilege);
        if (isUpdate) {
            return R.ok("修改失败");
        }
        return R.fail("修改成功");
    }

}
